﻿using Microsoft.AspNetCore.SignalR;

namespace DevSupport.Hubs
{
    public class ChatHub : Hub<IChatClient>
    {
        /// <summary>
        /// 给所有客户端发送消息
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="message">消息</param>
        /// <returns></returns>
        public async Task SendMessage(string title, string message)
        {
            //await Clients.All.ReceiveMessage(user, message);

            await Clients.All.WebMessage(title, message);
        }

        /// <summary>
        /// 向调用客户端发送消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessageCaller(string message)
        {
            await Clients.Caller.ReceiveCaller(message); 
        }

        /// <summary>
        /// 向指定客户端发送消息
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="title"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessageToOne(string Id, string title, string message)
        {
            await Clients.Client(Id).WebMessage(title, message);
             
        }
        /// <summary>
        /// 客户端连接服务端
        /// </summary>
        /// <returns></returns>
        public override Task OnConnectedAsync()
        {
            //var id = Context.ConnectionId;
            var info = new OnLineInfo
            {
                Id = Context.ConnectionId,
                Name = Context.ConnectionId,
                LoginTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm")
            };
            WebOnLine.OnLineList.Add(info); 

            Clients.All.ListenerOnline(WebOnLine.OnLineCount); 

            return base.OnConnectedAsync();
        }

        /// <summary>
        /// 客户端断开连接
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override Task OnDisconnectedAsync(Exception exception)
        {
            var id = Context.ConnectionId; 
            WebOnLine.OnLineList.RemoveAll(c=>c.Id == id);  
            Clients.All.ListenerOnline(WebOnLine.OnLineCount); 
            return base.OnDisconnectedAsync(exception);
        }

        public async Task ReceiveLog(object data)
        { 
            await Clients.All.ReceiveLog(data);
        }
    } 
}